package com.qili.controller;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.controller.BaseController;
import com.qili.base.entity.CurrentUser;
import com.qili.core.annotation.Log;
import com.qili.core.shiro.Principal;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseDict;
import com.qili.entity.exam.*;
import com.qili.entity.exam.dto.ExPaperDTO;
import com.qili.entity.exam.dto.ExQuestionDTO;
import com.qili.entity.sys.SysLog;
import com.qili.exception.MyException;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.service.base.BaseDictService;
import com.qili.service.exam.ExPaperQuestionService;
import com.qili.service.exam.ExPaperService;
import com.qili.service.exam.ExQuAnswerService;
import com.qili.service.exam.ExQuestionService;
import com.qili.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:zyl
 * @Description:
 */
@Controller
@Slf4j
@RequestMapping("/ex/exPaper")
public class exPaperController extends BaseController {

    @Autowired
    ExPaperService exPaperService;
    @Autowired
    ExPaperQuestionService exPaperQuestionService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    ExQuestionService exQuestionService;
    @Autowired
    ExQuAnswerService exQuAnswerService;
    private ExTree tree;
    @Autowired
    SysLogMapper sysLogMapper;

    /**
     * 试卷库页面
     *
     * @param model
     * @return
     */
    @GetMapping(value = "/sjkIndex")
    @RequiresPermissions("zh:sjk")
    public String sjkList(Model model) {
        //试题题型
//        List<BaseDict> sttx = baseDictService.selectByTypeCode(DictTypes.SJFL.getType());
//        model.addAttribute("sttx", sttx);
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtGroupid("SJFL");
        List<BaseDict> sjfl = baseDictService.select(baseDict);
        model.addAttribute("sttx", sjfl);
        return "synthesize/sjk/sjList";
    }

    /**
     * 回收站页面
     *
     * @return
     */
    @GetMapping(value = "/recyclePaper")
    public String recyclePaper() {
        return "synthesize/sjk/recyclePaper";
    }

    /**
     * 跳转试卷新增页面
     *
     * @return
     */
    @GetMapping(value = "/sjkAdd")
    public String sjkAdd(Model model) {
        String uuid = CommonUtil.getRandomUUID();
        //试题题型
        List<BaseDict> sttx = baseDictService.selectByTypeCode(DictTypes.STTX.getType());
        //试卷类型
        List<BaseDict> sjlx = baseDictService.selectByTypeCode("SJLX");
        //试题分类
//        List<BaseDict> stfl = baseDictService.selectByTypeCode("STFL");
        BaseDict baseDict1 = new BaseDict();
        baseDict1.setBadtGroupid("STFL");
        List<BaseDict> stfl = baseDictService.select(baseDict1);
        //试卷分类
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtGroupid("SJFL");
        List<BaseDict> sjfl = baseDictService.select(baseDict);
        //试题难度
        baseDict.setBadtGroupid("STND");
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.STND.getType());
        // 试题数量
        ExQuestion exQuestion = new ExQuestion();
        exQuestion.setStatus("002");
        int x = exQuestionService.selectCount(exQuestion);
        model.addAttribute("stnd", stnd);
        model.addAttribute("sttx", sttx);
        model.addAttribute("sjfl", sjfl);
        model.addAttribute("stfl", stfl);
        model.addAttribute("count", x);
        model.addAttribute("id", uuid);
        model.addAttribute("sjlx", sjlx);
        return "synthesize/sjk/paperAdd";
    }

    /**
     * 查询试题分类，树显示
     * @Param paperSort 试题分类id - 编辑回显的时候用到
     * @return
     */
    @GetMapping(value = "/selectTypeClassify")
    @ResponseBody
    public ReType selectTypeClassify(String paperSort,String identifying){
        List<Map<String,Object>> treeDtoList = null;
        try {
            BaseDict baseDict = new BaseDict();
            baseDict.setBadtTypecode("SJFL");
            List<BaseDict> sjfl = baseDictService.select(baseDict); // 查询的第一级
            treeDtoList = new ArrayList<>();
            // 添加选择分类，什么也不选择
            if (StringUtil.isNotBlank(identifying)){
                Map<String,Object> defaultData = new HashMap<>();
                defaultData.put("id","");
                defaultData.put("title","请选择分类");
                defaultData.put("children","");
                treeDtoList.add(defaultData);
            }
            for (BaseDict dict : sjfl) {
                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("id",dict.getBadtCode());
                resultMap.put("title",dict.getBadtName());
                // 判断是否存在对应的参数，需要默认选中
                if (StringUtil.isNotBlank(paperSort)){
                    if (dict.getBadtCode().equals(paperSort)){
                        resultMap.put("checked","true");
                    }
                }
                // 查询当前结点的子节点
                BaseDict bd = new BaseDict();
                bd.setBadtGroupid("SJFL");
                bd.setBadtTypecode(dict.getBadtCode());
                List<BaseDict> erSjfl = baseDictService.select(bd); // 当前结点下的子节点集合
                List<Map<String,String>> tempErTree = new ArrayList<>();
                if (erSjfl != null && erSjfl.size() > 0){
                    for (BaseDict baseDict2 : erSjfl) {
                        Map<String, String> stringMap = new HashMap<>();
                        stringMap.put("id",baseDict2.getBadtCode());
                        stringMap.put("title",baseDict2.getBadtName());
                        stringMap.put("children","");
                        if (!StringUtil.isNotBlank(paperSort) && baseDict2.getBadtCode().equals(paperSort)){
                            stringMap.put("checked","true");
                        }
                        tempErTree.add(stringMap);
                    }
                }
                resultMap.put("children",tempErTree);
                treeDtoList.add(resultMap);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ReType.success(200,"成功",treeDtoList);
    }

    /**
     * 跳转试卷编辑页面
     *
     * @return
     */
    @GetMapping(value = "/sjkUpdate")
    public String sjkUpdate(Model model, ExPaper eq) {
        //试题
        ExPaper exQuestion = exPaperService.selectOne(eq);
        model.addAttribute("eq", exQuestion);
        //试题题型
        List<BaseDict> sttx = baseDictService.selectByTypeCode(DictTypes.STTX.getType());
        model.addAttribute("sttx", sttx);
        //试题分类
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtGroupid("STFL");
        List<BaseDict> stfl = baseDictService.select(baseDict);
        model.addAttribute("stfl", stfl);
        //试卷分类
        baseDict.setBadtGroupid("SJFL");
        List<BaseDict> sjfl = baseDictService.select(baseDict);
        model.addAttribute("sjfl", sjfl);
        //试题难度
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.STND.getType());
        model.addAttribute("stnd", stnd);
        // 试题数量
        ExQuestion exQuestion2 = new ExQuestion();
        exQuestion2.setStatus("002");
        int x = exQuestionService.selectCount(exQuestion2);
        model.addAttribute("count", x);
        return "synthesize/sjk/paperEdit";
    }

    /**
     * 跳转试卷详情页面
     *
     * @return
     */
    @GetMapping(value = "/sjDetail")
    @RequiresRoles("ksgly")
    public String sjDetail(Model model, ExPaper eq) {
        //试题
        ExPaper exQuestion = exPaperService.selectOne(eq);
        model.addAttribute("eq", exQuestion);
        //试题题型
        List<BaseDict> sttx = baseDictService.selectByTypeCode(DictTypes.STTX.getType());
        model.addAttribute("sttx", sttx);
        //试题分类
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtGroupid("SJFL");
        List<BaseDict> stfl = baseDictService.select(baseDict);
        model.addAttribute("stfl", stfl);
        //试题难度
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.STND.getType());
        model.addAttribute("stnd", stnd);
        return "synthesize/sjk/paperDetail";
    }

    /**
     * 试卷库列表查询
     *
     * @param dto
     * @param model
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/sjkList")
    @ResponseBody
    public ReType sjkList(ExPaperDTO dto, Model model, int page, int limit) {
        List<ExPaper> sjkList = null;
        //试题分类查询当前目录和下级目录数据
        if (!"SJFL".equals(dto.getPaperSort())) {
            if (StringUtil.isNotBlank(dto.getPaperSort())) {
                List<String> list = new ArrayList<>();
                list.add(dto.getPaperSort());
                ExTree exTree = new ExTree();
                exTree.setId(dto.getPaperSort());
                List<ExTree> treeList = selectTreeList(exTree);
                for (int i = 0; i < treeList.size(); i++) {
                    list.add(treeList.get(i).getId());
                }
                dto.setTreeList(list);
            }
        }
        Page<ExPaper> tPage = PageHelper.startPage(page, limit);
        try {
            sjkList = exPaperService.selectExPaper(dto);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), sjkList);
    }

    /**
     * 试题库列表查询
     *
     * @param id
     * @param model
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/stkList")
    @ResponseBody
    public ReType stkList(String id, Model model, Integer page, Integer limit) {
        List<ExQuestion> sjkList = null;
        if (page == null) {
            page = 1;
        }
        if (limit == null) {
            limit = Integer.MAX_VALUE;
        }
        Page<ExQuestion> tPage = PageHelper.startPage(page, limit);
        try {
            sjkList = exPaperService.stList(id);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), sjkList);
    }

    /**
     * 试题库查询选中的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/pitchList")
    @ResponseBody
    public ReType pitchList(String id) {
        ReType reType = new ReType();
        List<ExQuestion> sjkList = null;
        try {
            sjkList = exPaperService.stList(id);
        } catch (MyException e) {
            e.printStackTrace();
            reType.setCode(500);
            reType.setMsg("查询失败！");
            return reType;
        }
        reType.setCode(200);
        reType.setData(sjkList);
        return reType;
    }

    /**
     * 试卷库删除
     *
     * @param id   当type 为 2 时 为关系表主键id type为1时 为试卷id
     * @param type type 1 删除所有 type 2 删除单个
     * @param classify 不为空并且是 'del' ,需要修改试卷的 试题总分 & 试题总数
     * @param score 当前试题的分数
     * @return
     */
    @Log(desc = "从试卷列表中删除试题", type = Log.LOG_TYPE.DEL)
    @GetMapping(value = "/deleteList")
    @ResponseBody
    public ReType deleteList(String id, String type,String classify,String score) {
        ReType reType = new ReType();
        if ("1".equals(type)) {
            //根据试卷关系 删除当前试卷下所有关联试题
            exPaperQuestionService.deleteByPaperId(id);
            reType.setCode(1);
        } else {
            //先根据关系表主键查询关系表试卷的paper_id
            String paperId = exPaperQuestionService.selectPaperIdByPaperQuId(id);
            // 2021年12月8日13:58:37 新增-需要修改试卷的 试题总分 & 试题总数
            if (StringUtil.isNotBlank(classify) && "del".equals(classify)){
                ExPaper exPaper = exPaperService.selectByPrimaryKey(paperId);
                if (StringUtil.isNotBlank(exPaper.getTotalNum())){
                    int num = Integer.parseInt(exPaper.getTotalNum()) - 1;
                    exPaper.setTotalNum(String.valueOf(num));
                }
                if (StringUtil.isNotBlank(exPaper.getTotalScore())){
                    int scoreT = Integer.parseInt(exPaper.getTotalScore()) - Integer.parseInt(score);
                    exPaper.setTotalScore(String.valueOf(scoreT));
                }
                // 进行更新试卷
                exPaperService.updateByPrimaryKey(exPaper);
            }
            //根据试卷->试题关联关系表主键删除单条试题
            exPaperQuestionService.deleteByPrimaryKey(id);
            //删除之后用刚才查到的试卷id  查询这个试卷下还有没有其他试题
            List<String> paperQuIds = exPaperQuestionService.selectPaperQuIdByPaperId(paperId);
            //如果没有 直接返回
            if (paperQuIds == null || paperQuIds.size() <= 0) {
                reType.setCode(1);
                return reType;
            }
            //如果有 重新排序修改
            int count = 0;
            for (String paperQuId : paperQuIds) {
                exPaperQuestionService.updateOrderNoByPaperQuId(paperQuId, ++count);
            }
            reType.setCode(1);
        }
        return reType;
    }

    /**
     * 试题库列表查询
     *
     * @param exQuestionDTO
     * @param model
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/stkListByType")
    @ResponseBody
    public ReType stkListByType(ExQuestionDTO exQuestionDTO, Model model, int page, int limit) {
        List<ExQuestion> sjkList = null;
        //试题分类查询当前目录和下级目录数据
        if (!"STFL".equals(exQuestionDTO.getQuCategory())) {
            if (StringUtil.isNotBlank(exQuestionDTO.getQuCategory())) {
                List<String> list = new ArrayList<>();
                list.add(exQuestionDTO.getQuCategory());
//                ExTree exTree = new ExTree();
//                exTree.setId(exQuestionDTO.getQuCategory());
//                List<ExTree> treeList = selectTreeList(exTree);
                List<ExTree> treeList = selectSubordinateTrees(exQuestionDTO.getQuCategory(), "STFL");
                for (int i = 0; i < treeList.size(); i++) {
                    list.add(treeList.get(i).getId());
                }
                exQuestionDTO.setTreeList(list);
            }
        }
        Page<ExQuestion> tPage = PageHelper.startPage(page, limit);
        try {
            sjkList = exPaperService.stListByType(exQuestionDTO);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), sjkList);
    }

    /**
     * 递归查出试题分类数据-【2021年11月15日13:29:50】
     *
     * @param id
     * @param groupid
     * @return
     */
    public List<ExTree> selectSubordinateTrees(String id, String groupid) {
        List<ExTree> list = exPaperService.selectSubordinateTrees(id, groupid);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                List<ExTree> list1 = selectSubordinateTrees(list.get(i).getId(),groupid);
                list.get(i).setChildren(list1);
            }
        }
        return list;
    }

    /**
     * ZYL
     * 新增试卷
     *
     * @param exPaper
     * @return
     */
    @GetMapping(value = "/insertPaper")
    @ResponseBody
    @RequiresRoles("ksgly")
    public ReType insertGDPaper(ExPaper exPaper) {
        String paperName = exPaper.getPaperName();
        String paperSort = exPaper.getPaperSort();
        String paperType = exPaper.getPaperType();
        if (paperName == null || "".equals(paperName)) {
            return ReType.error("试卷名称不能为空");
        }
        if (paperSort == null || "".equals(paperSort)) {
            return ReType.error("试卷分类不能为空");
        }
        if (paperType == null || "".equals(paperType)) {
            return ReType.error("试卷类型不能为空");
        }
        ExPaperQuestion exPaperQuestion = new ExPaperQuestion();
        exPaperQuestion.setPaperId(exPaper.getPaperId());
        exPaper.setTotalNum(exPaperQuestionService.selectCount(exPaperQuestion) + "");
        exPaper.setCreateBy(CommonUtil.getUserId());
        exPaper.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        exPaperService.insert(exPaper);
        if ("001".equals(exPaper.getStatus())) {
            insertFileLog("新增试卷","参数："+exPaper.getPaperName(),"ADD");
            return ReType.success(1, "保存成功");
        } else {
            return ReType.success(1, "提交成功");
        }
    }

    /**
     * 根据id修改试卷 名称 分类 类型 等字段
     *
     * @param exPaper
     * @return
     */
    @PostMapping(value = "/updatePaperByUuid")
    @ResponseBody
    @RequiresRoles("ksgly")
    public ReType updatePaperByUuid(@RequestBody ExPaper exPaper) {
        String paperName = exPaper.getPaperName();
        String paperSort = exPaper.getPaperSort();
        String paperType = exPaper.getPaperType();
        if (paperName == null || "".equals(paperName)) {
            return ReType.error("试卷名称不能为空");
        }
        if (paperSort == null || "".equals(paperSort)) {
            return ReType.error("试卷分类不能为空");
        }
        if (paperType == null || "".equals(paperType)) {
            return ReType.error("试卷类型不能为空");
        }
        exPaper.setModifyDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        exPaper.setModifyBy(CommonUtil.getUserId());
        exPaperService.updateByPrimaryKeySelective(exPaper);

        //删除之前所有关联的试题
        exPaperQuestionService.deleteByPaperId(exPaper.getPaperId());
        //取出试卷选择的试题列表
        List<JSONObject> paperDetails = exPaper.getPaperDetails();
        int count = 0;
        for (JSONObject paperDetail : paperDetails) {
            ExPaperQuestion exPaperQuestion = new ExPaperQuestion();
            exPaperQuestion.setPaperQuId(CommonUtil.getRandomUUID());
            exPaperQuestion.setPaperId(exPaper.getPaperId());
            exPaperQuestion.setQuId(paperDetail.getString("quId"));
            exPaperQuestion.setScore(paperDetail.getString("score"));
            exPaperQuestion.setOrderNo(++count);
            exPaperQuestion.setCreateBy(CommonUtil.getUserId());
            exPaperQuestion.setCreateDate(CommonUtil.getCurrentTimeStr());
            exPaperQuestionService.insert(exPaperQuestion);
        }
        insertFileLog("更新试卷","参数："+exPaper.getPaperName(),"UPDATE");
        return ReType.success(1, "修改成功");
    }

    /**
     * 根据id修改试卷 名称 分类 类型 等字段 - 重写
     *
     * @param exPaper
     * @return
     */
    @PostMapping(value = "/updatePaperSubmit")
    @ResponseBody
    @RequiresRoles("ksgly")
    public ReType updatePaperSubmit(@RequestBody ExPaper exPaper) {
        String paperName = exPaper.getPaperName();
        String paperSort = exPaper.getPaperSort();
        String paperType = exPaper.getPaperType();
        if (paperName == null || "".equals(paperName)) {
            return ReType.error("试卷名称不能为空");
        }
        if (paperSort == null || "".equals(paperSort)) {
            return ReType.error("试卷分类不能为空");
        }
        if (paperType == null || "".equals(paperType)) {
            return ReType.error("试卷类型不能为空");
        }
        exPaper.setModifyDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        exPaper.setModifyBy(CommonUtil.getUserId());
        // 查询当前问题数量
        int num = exPaperQuestionService.selectNumByPaperId(exPaper.getPaperId());
        if (0 != num){
            exPaper.setTotalNum(String.valueOf(num));
        }
        exPaperService.updateByPrimaryKeySelective(exPaper);
        insertFileLog("更新试卷","参数："+exPaper.getPaperName(),"UPDATE");
        return ReType.success(1, "修改成功");
    }


    /**
     * ZYL
     * 新增固定试卷关联关系
     *
     * @param id
     * @param strs
     * @param score
     * @param paperType
     * @param paperSort
     * @param paperName
     * @param model
     * @param classify 类型，不为空并且是 'edit' ,需要修改试卷的 试题总分 & 试题总数
     * @return
     */
    @GetMapping(value = "/insertPaperRelGd")
    @ResponseBody
    public ReType insertPaper(String id, String[] strs, String score, String paperType, String paperSort, String paperName, Model model, String classify) {
        if (strs.length == 0) {
            return ReType.error("参数有误");
        }
        try {
            ExPaperQuestion exPaperQuestion2 = new ExPaperQuestion();
            exPaperQuestion2.setPaperId(id);
            int count = exPaperQuestionService.selectCount(exPaperQuestion2);
            int counter = 0;
            for (int i = 0; i < strs.length; i++) {
                if (strs[i] == null || "".equals(strs[i])) {
                    continue;
                }
                ExPaperQuestion exPaperQuestion = new ExPaperQuestion();
                exPaperQuestion.setPaperQuId(CommonUtil.getRandomUUID());
                exPaperQuestion.setPaperId(id);
                exPaperQuestion.setQuId(strs[i]);
                exPaperQuestion.setScore(score);
                exPaperQuestion.setCreateBy(CommonUtil.getUserId());
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                exPaperQuestion.setCreateDate(formatter.format(new Date()));
                exPaperQuestion.setOrderNo(++count);
                exPaperQuestionService.insert(exPaperQuestion);
                counter++;
            }
            // 处理需要修改试卷的 试题总分 & 试题总数
            if (StringUtil.isNotBlank(classify) && "edit".equals(classify)){
                // 查询当前试卷
                ExPaper exPaper = exPaperService.selectByPrimaryKey(id);
                if (0 != counter){
                    if (StringUtil.isNotBlank(exPaper.getTotalScore())){
                        int scoreT = Integer.parseInt(exPaper.getTotalScore()) + (counter * Integer.parseInt(score));
                        exPaper.setTotalScore(String.valueOf(scoreT));
                    }
                    if (StringUtil.isNotBlank(exPaper.getTotalNum())){
                        int num = Integer.parseInt(exPaper.getTotalNum()) + counter;
                        exPaper.setTotalNum(String.valueOf(num));
                    }
                    // 进行更新试卷
                    exPaperService.updateByPrimaryKey(exPaper);
                }

            }
        } catch (MyException e) {
            e.printStackTrace();
        }
        ReType reType = new ReType();
        reType.setCode(1);
        return reType;
    }

    /**
     * ZYL
     * 新增随机试卷关联关系
     *
     * @param exPaperDTO
     * @param classify 类型，不为空并且是 'edit' ,需要修改试卷的 试题总分 & 试题总数
     * @return
     */
    @GetMapping(value = "insertPaperRelSj")
    @ResponseBody
    public JsonUtil insertPaperRelSj(ExPaperDTO exPaperDTO,String classify) {
        exPaperDTO.setStr(Integer.parseInt(exPaperDTO.getNum()));
        if (!"STFL".equals(exPaperDTO.getQuCategory())) {
            if (StringUtil.isNotBlank(exPaperDTO.getQuCategory())) {
                List<String> list = new ArrayList<>();
                list.add(exPaperDTO.getQuCategory());
                List<ExTree> treeList = selectSubordinateTrees(exPaperDTO.getQuCategory(), "STFL");
                for (int i = 0; i < treeList.size(); i++) {
                    list.add(treeList.get(i).getId());
                }
                exPaperDTO.setTreeList(list);
            }
        }
        List<String> list = exPaperService.insertPaperSj(exPaperDTO);
        if (list == null || list.size() <= 0 || list.size() < Integer.parseInt(exPaperDTO.getNum())) {
            return JsonUtil.error("未查询到足够试题");
        }
        //试题id
        //每次新增都要查询之前有无明细 如果有 排序需要接下去
        ExPaperQuestion param = new ExPaperQuestion();
        param.setPaperId(exPaperDTO.getId());
        int count = exPaperQuestionService.selectCount(param);
        int counter = 0;
        for (int i = 0; i < list.size(); i++) {
            //试题试卷关联表
            ExPaperQuestion exPaperQuestion = new ExPaperQuestion();
            //试题id
            exPaperQuestion.setQuId(list.get(i));
            //序号
            exPaperQuestion.setOrderNo(++count);
            //分数
            exPaperQuestion.setScore(exPaperDTO.getScore());
            //试卷id
            exPaperQuestion.setPaperId(exPaperDTO.getId());
            exPaperQuestionService.insert(exPaperQuestion);
            counter++;
        }
        // 处理需要修改试卷的 试题总分 & 试题总数
        if (StringUtil.isNotBlank(classify) && "edit".equals(classify)){
            // 查询当前试卷
            ExPaper exPaper = exPaperService.selectByPrimaryKey(exPaperDTO.getId());
            if (0 != counter){
                if (StringUtil.isNotBlank(exPaper.getTotalScore())){
                    int scoreT = Integer.parseInt(exPaper.getTotalScore()) + (counter * Integer.parseInt(exPaperDTO.getScore()));
                    exPaper.setTotalScore(String.valueOf(scoreT));
                }
                if (StringUtil.isNotBlank(exPaper.getTotalNum())){
                    int num = Integer.parseInt(exPaper.getTotalNum()) + counter;
                    exPaper.setTotalNum(String.valueOf(num));
                }
                // 进行更新试卷
                exPaperService.updateByPrimaryKey(exPaper);
            }
        }
        return JsonUtil.sucess("添加成功");
    }

    /**
     * 根据条件随机获取几个试题
     *
     * @param exPaperDTO
     * @return
     */
    @GetMapping(value = "getPaperRelSj")
    @ResponseBody
    public ReType getPaperRelSj(ExPaperDTO exPaperDTO) {
        exPaperDTO.setStr(Integer.parseInt(exPaperDTO.getNum()));
        List<Map<String, Object>> list = exPaperService.selectRandomSt(exPaperDTO);
        if (list == null || list.size() <= 0 || list.size() < Integer.parseInt(exPaperDTO.getNum())) {
            return ReType.error("未查询到足够试题");
        }
        return ReType.success(1, "添加成功", list);
    }

    /**
     * 试卷库回收站查询
     *
     * @param dto
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/recyclePaperList")
    @ResponseBody
    public ReType recyclePaperList(ExPaper dto, int page, int limit) {
        List<ExPaper> sjkList = null;
        Page<ExPaper> tPage = PageHelper.startPage(page, limit);
        // dto.setStatus("003");
        try {
            // sjkList = exPaperService.selectExQuestion(exPaperDTO);
            sjkList = exPaperService.selectRecycle(dto);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), sjkList);
    }


    /**
     * 数据还原
     *
     * @param eq
     * @return
     */
    @GetMapping(value = "/updateHy")
    @ResponseBody
    public JsonUtil updateHy(ExPaper eq) {
        JsonUtil json = new JsonUtil();
        // 查询删除之前的状态
        ExPaper exPaper = exPaperService.selectByPrimaryKey(eq.getPaperId());
        if (!StringUtil.isBlank(exPaper.getReductionType())){
            eq.setStatus(exPaper.getReductionType());
        }
        eq.setCreateBy(CommonUtil.getUserId());
        eq.setCreateDate(DateUtil.getCurrentDateString());
        if (exPaperService.updateByPrimaryKeySelective(eq) > 0) {
            json.setFlag(true);
            return json;
        }
        json.setFlag(false);
        return json;
    }

    /**
     * 试卷库删除
     *
     * @param eq
     * @return
     */
    // @GetMapping(value = "/updateSjStatus")
    @GetMapping(value = "deleteSj")
    @ResponseBody
    @RequiresRoles("ksgly")
    public JsonUtil deleteSj(ExPaper eq, String[] ids, String state) {
        JsonUtil json = new JsonUtil();
        try {
            //ids有值走批量
            if (ids != null && ids.length > 0 && StringUtils.isNotBlank(state)) {
                // 需要先判断删除前的类型
                for (String id : ids) {
                    ExPaper exPaper = exPaperService.selectByPrimaryKey(id);
                    String type = "";
                    if (!StringUtil.isBlank(exPaper.getReductionType())){
                        type = exPaper.getStatus();
                    }
                    // 封装参数
                    Map<String, Object> map = new HashMap();
                    map.put("id", id);
                    map.put("status", state);
                    map.put("modifyBy", CommonUtil.getUserId());
                    map.put("modifyDate", DateUtil.getCurrentDateString());
                    // 2021年11月24日 新增还原之前的类型
                    map.put("reductionType", type);
                    exPaperService.deleteSjsN(map);
                }
            } else {
                eq.setStatus(state);
                eq.setModifyBy(CommonUtil.getUserId());
                eq.setModifyDate(DateUtil.getCurrentDateString());
                exPaperService.updateByPrimaryKeySelective(eq);
            }
            json.setFlag(true);
            return json;
        }catch (Exception e) {
            e.printStackTrace();
            json.setFlag(false);
            return json;
        }
    }

    /**
     * 试卷库回收站删除全部
     *
     * @return
     */

    @GetMapping(value = "/deleteAll")
    @ResponseBody
    public JsonUtil deleteAll() {
        JsonUtil json = new JsonUtil();
        try {
            ExPaper eq = new ExPaper();
            eq.setStatus("003");
            // if (exPaperService.delete(eq) > 0) {
            List<ExPaper> select = exPaperService.select(eq);
            deleteAll(select);
            json.setFlag(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(false);
            json.setMsg("删除失败");
        }
        return json;
    }

    public void deleteAll(List<ExPaper> select) {
        if (select != null) {
            if (select.size() > 0) {
                for (int i = 0; i < select.size(); i++) {
                    ExPaper exPaper = select.get(i);
                    SysLog sysLog = new SysLog();
                    sysLog.setCreateTime(new Date());
                    sysLog.setType("DEL");
                    sysLog.setText("从回收站中删除试卷");
                    sysLog.setParam("参数：" + exPaper.getPaperName());
                    sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
                    CurrentUser currentUser = Principal.getCurrentUse();
                    sysLog.setUserName(currentUser.getUsername());
                    sysLogMapper.insert(sysLog);
                    exPaperService.delete(exPaper);
                }
            }
        }
    }


    /**
     * 试卷库回收站删除
     *
     * @return
     */

    @GetMapping(value = "delFromRecycle")
    @ResponseBody
    public JsonUtil delFromRecycle(String paperId) {
        if (StringUtil.isBlank(paperId)) {
            return JsonUtil.error("参数有误");
        }
        ExPaper exPaper = exPaperService.selectByPrimaryKey(paperId);
        int count = exPaperService.delFormRecycle(paperId);
        if (count > 0) {
            insertFileLog("从回收站中删除试卷","参数："+exPaper.getPaperName(),"DEL");
            return JsonUtil.sucess("删除成功");
        } else {
            return JsonUtil.error("删除失败");
        }
    }

    /**
     * 试卷库回收站批量删除
     *
     * @return
     */
    @PostMapping(value = "deleteFromRecycle")
    @ResponseBody
    public JsonUtil deleteFromRecycle(@RequestBody String[] ids) {
        try {
            if (ids == null || ids.length <= 0) {
                return JsonUtil.error("参数有误");
            }
            for (String id : ids) {
                ExPaper exPaper = exPaperService.selectByPrimaryKey(id);
                insertFileLog("从回收站中删除试卷","参数："+exPaper.getPaperName(),"DEL");
            }

            int count = exPaperService.deleteFromRecycle(ids);
            if (count > 0) {
                return JsonUtil.sucess("删除成功。");
            }
            return JsonUtil.error("删除失败。");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("删除失败，" + e.getMessage());
        }
    }

    /**
     * 试卷库回收站批量还原
     *
     * @return
     */
    @PostMapping(value = "/hyAll")
    @ResponseBody
    public JsonUtil hyAll(@RequestBody String[] ids) {
        try {
            if (ids == null || ids.length <= 0) {
                return JsonUtil.error("参数有误");
            }
            // 判断当前删除之前是什么状态
            for (String id : ids) {
                ExPaper exPaper = exPaperService.selectByPrimaryKey(id);
                String type = "001";
                if (!StringUtil.isBlank(exPaper.getReductionType())){
                    type = exPaper.getReductionType();
                }
                // 去执行更新操作 2021年11月24日14:44:39 新加
                exPaperService.hyAllN(id, type);
            }
            return JsonUtil.sucess("还原成功。");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("还原失败，" + e.getMessage());
        }
    }

    /**
     * 查询试题分类
     *
     * @param tree
     * @return
     */
    @GetMapping(value = "/selectTree")
    @ResponseBody
    public List<ExTree> selectTree(ExTree tree) {
        //查询出第一级
        List<ExTree> trList = exPaperService.selectTree(tree);
        List<ExTree> list = new ArrayList<>();
        list = selectTreeList(trList.get(0));
        if (list != null) {
            trList.get(0).setChildren(list);
        }
        return trList;
    }


    /**
     * 递归查出试题分类数据
     *
     * @param tree
     * @return
     */
    public List<ExTree> selectTreeList(ExTree tree) {
        List<ExTree> list = exPaperService.selectTrees(tree);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                List<ExTree> list1 = selectTreeList(list.get(i));
                list.get(i).setChildren(list1);
            }
        }
        return list;
    }

    /**
     * 修改试卷分类节点
     *
     * @param request
     * @return
     */
    @GetMapping(value = "updateTree")
    @ResponseBody
    public JsonUtil updateTree(HttpServletRequest request) {
        JsonUtil js = new JsonUtil();
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        Map map = new HashMap();
        map.put("name", name);
        map.put("id", id);
        int i = 0;
        i = exPaperService.updateTree(map);
        if (i > 0) {
            js.setFlag(true);
        } else {
            js.setFlag(false);
        }
        return js;
    }

    /**
     * 新增试卷分类节点
     *
     * @param request
     * @return
     */
    @GetMapping(value = "insertTree")
    @ResponseBody
    public JsonUtil insertTree(HttpServletRequest request) {
        JsonUtil js = new JsonUtil();
        String id = request.getParameter("parentRoleId");
        String name = request.getParameter("name");
        String treeId = IdUtil.simpleUUID();
        Map map = new HashMap();
        map.put("badtName", name);
        map.put("badtTypecode", id);
        map.put("badtCode", treeId);
        map.put("badtGroupid", "SJFL");
        int i = 0;
        i = exPaperService.insertTree(map);
        if (i > 0) {
            js.setFlag(true);
            js.setData(treeId);
        } else {
            js.setFlag(false);
        }
        return js;
    }

    /**
     * 删除试卷分类节点
     *
     * @param request
     * @return
     */
    @Log(desc = "删除试卷分类节点", type = Log.LOG_TYPE.DEL)
    @GetMapping(value = "deleteTree")
    @ResponseBody
    public JsonUtil deleteTree(HttpServletRequest request) {
        JsonUtil js = new JsonUtil();
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtCode(id);
        baseDict.setBadtGroupid("SJFL");
        try {
            int i = 0;
            if (StringUtil.isNotBlank(id)) {
                i = baseDictService.delete(baseDict);
            } else {
                i = 0;
            }
            if (i > 0) {
                js.setFlag(true);
            } else {
                js.setFlag(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return js;
    }

    /**
     * 删除前判断是否被引用
     *
     * @param request
     * @return
     */
    @GetMapping(value = "deleteHint")
    @ResponseBody
    public JsonUtil deleteHint(HttpServletRequest request) {
        JsonUtil js = new JsonUtil();
        String id = request.getParameter("id");
        ExPaper exPaper = new ExPaper();
        exPaper.setPaperSort(id);
        List<ExPaper> exList = exPaperService.select(exPaper);
        //判断是否被引用
        if (exList != null && exList.size() > 0) {
            js.setMsg("该分类被引用不可删除");
            js.setFlag(false);
            return js;
        } else {
            //判断下面节点是否被引用
            ExTree tree = new ExTree();
            tree.setId(id);
            List<ExTree> list = exPaperService.selectTrees(tree);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    ExPaper ep = new ExPaper();
                    ep.setPaperSort(list.get(i).getId());
                    List<ExPaper> epList = exPaperService.select(ep);
                    //判断是否被引用
                    if (epList != null && epList.size() > 0) {
                        js.setMsg("该分类下节点被引用不可删除");
                        js.setFlag(false);
                        return js;
                    }
                }
            }
        }
        js.setFlag(true);
        return js;
    }

    /**
     * 根据试卷id查询试卷总分数
     *
     * @param paperId
     * @return
     */
    @GetMapping("refreshTotalScore")
    @ResponseBody
    public int refreshTotalScore(String paperId) {
        Integer totalScore = exPaperService.refreshTotalScore(paperId);
        if (totalScore == null) {
            return 0;
        }
        return totalScore;
    }


    /**
     * 根据试卷id查询试题总数
     *
     * @param paperId
     * @return
     */
    @GetMapping("refreshTotalNum")
    @ResponseBody
    public int refreshTotalNum(String paperId) {
        Integer totalNum = exPaperService.refreshTotalNum(paperId);
        if (totalNum == null) {
            return 0;
        }
        return totalNum;
    }

    /**
     * 批量提交试卷
     *
     * @param ids
     * @return
     */
    @GetMapping("updateBatchPaperStatus")
    @ResponseBody
    @RequiresRoles("ksgly")
    public JsonUtil updateBatchPaperStatus(String[] ids) {
        if (ids == null || ids.length <= 0) {
            return JsonUtil.error("未获取到已选择试卷");
        }
        for (String id : ids) {
            Map<String, Object> map = exPaperService.selectPaperQuCountById(id);
            if (0 == (long) map.get("quCount")) {
                return JsonUtil.error("试卷" + map.get("paper_name") + "不包含试题,提交失败");
            }
        }
        int count = exPaperService.updateBatchPaperStatus(ids);
        if (count > 0) {
            return JsonUtil.sucess("提交成功 本次共提交" + count + "条");
        } else {
            return JsonUtil.error("选中有已提交的数据,请重新选");
        }
    }

    /**
     * 跳转试题详情页面
     *
     * @return
     */
    @GetMapping(value = "/stkDetail")
    public String stkDetail(Model model, ExQuestion eq) {
        //试题
        ExQuestion exQuestion = exQuestionService.selectOne(eq);
        model.addAttribute("eq", exQuestion);
        //答案
        Example ecj = new Example(ExQuAnswer.class);
        Example.Criteria ccj = ecj.createCriteria();
        ccj.andEqualTo("quId", eq.getQuId());
        ecj.setOrderByClause("serial ASC");
        List<ExQuAnswer> exq = exQuAnswerService.selectByExample(ecj);
        model.addAttribute("exq", exq);
        model.addAttribute("index", exq.size());
        //试题题型
        List<BaseDict> sttx = baseDictService.selectByTypeCode(DictTypes.STTX.getType());
        model.addAttribute("sttx", sttx);
        //试题分类
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtGroupid("STFL");
        List<BaseDict> stfl = baseDictService.select(baseDict);
        model.addAttribute("stfl", stfl);
        //试题难度
        List<BaseDict> stnd = baseDictService.selectByTypeCode(DictTypes.STND.getType());
        model.addAttribute("stnd", stnd);
        return "synthesize/sjk/itemBankDetail";
    }

    /**
     * 刷新随机试题可用数量
     *
     * @param exQuestion
     * @param quIds
     * @return
     */
    @GetMapping("refreshQuestionSjCanUse")
    @ResponseBody
    public int refreshQuestionSjCanUse(ExQuestion exQuestion, String[] quIds) {
//        int count = exQuestionService.selectCount(exQuestion);param1
        //试题分类查询当前目录和下级目录数据
        if (!"STFL".equals(exQuestion.getQuCategory())) {
            if (StringUtil.isNotBlank(exQuestion.getQuCategory())) {
                List<String> list = new ArrayList<>();
                list.add(exQuestion.getQuCategory());
                ExTree exTree = new ExTree();
                exTree.setId(exQuestion.getQuCategory());
                List<ExTree> treeList = selectTreeList(exTree,"STFL");
                for (int i = 0; i < treeList.size(); i++) {
                    list.add(treeList.get(i).getId());
                }
                exQuestion.setTreeList(list);
            }
        }
        return exPaperService.refreshQuestionSjCanUse(exQuestion, quIds);
    }

    /**
     * 递归查出试题分类数据
     * 2021年12月2日20:15:24 重写，带字典类型
     * @param tree
     * @return
     */
    public List<ExTree> selectTreeList(ExTree tree,String type) {
        List<ExTree> list = exPaperService.selectTreesByType(tree,type);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                List<ExTree> list1 = selectTreeList(list.get(i));
                list.get(i).setChildren(list1);
            }
        }
        return list;
    }

    //日志
    public void insertFileLog(String text,String param,String type ) {
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType(type);
        sysLog.setText(text);
        sysLog.setParam(param);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser currentUser = Principal.getCurrentUse();
        sysLog.setUserName(currentUser.getUsername());
        sysLogMapper.insert(sysLog);
    }

}
